<template>
	<div class="wrapper">
	  <!-- header部分 -->
	  <header>
		<i class="fa fa-angle-left" @click="goBack"></i>
		<p>在线支付</p>
	  </header>
	  <h3>订单信息：</h3>
	  <div class="order-info" v-if="orders">
		<p>
		  {{ orders.business ? orders.business.businessName : '加载中...' }}
		  <i class="fa" :class="isShowDetailet ? 'fa-caret-down' : 'fa-caret-right'" @click="detailetShow"></i>
		</p>
		<p>&#165;{{ orders.orderTotal }}</p>
	  </div>
	  <div v-else class="loading">
		<p>正在加载订单信息...</p>
	  </div>
	  <ul class="order-detailet" v-show="isShowDetailet && orders">
		<li v-for="detail in orderDetails" :key="detail.id">
		  <p>{{ detail.food ? detail.food.foodName : '商品' }} x {{ detail.quantity }}</p>
		  <p>&#165;{{ calculateItemTotal(detail) }}</p>
		</li>
		<li v-if="orders && orders.business">
		  <p>配送费</p>
		  <p>&#165;{{ orders.business.deliveryPrice }}</p>
		</li>
	  </ul>
  <h3>支付方式：</h3>
  <ul class="payment-type">
    <li @click="selectPaymentMethod('alipay')" :class="{ 'selected': selectedPaymentMethod === 'alipay' }">
      <img src="../assets/alipay.png" />
      <i class="fa fa-check-circle" v-show="selectedPaymentMethod === 'alipay'"></i>
    </li>
    <li @click="selectPaymentMethod('wechat')" :class="{ 'selected': selectedPaymentMethod === 'wechat' }">
      <img src="../assets/wechat.png" />
      <i class="fa fa-check-circle" v-show="selectedPaymentMethod === 'wechat'"></i>
    </li>
    <li @click="selectPaymentMethod('wallet')" :class="{ 'selected': selectedPaymentMethod === 'wallet' }" class="wallet-option">
      <div class="wallet-icon"><i class="fa fa-credit-card"></i></div>
      <span class="wallet-text">钱包支付</span>
      <i class="fa fa-check-circle" v-show="selectedPaymentMethod === 'wallet'"></i>
    </li>
  </ul>
  <div class="payment-button">
    <button @click="confirmPayment" :disabled="!orders || !orders.business || isPaymentProcessing">
      {{ isPaymentProcessing ? '支付处理中...' : '确认支付' }}
    </button>
  </div>
	  <Footer></Footer>
	</div>
  </template>
  
  <script setup>
  import Footer from "../components/Footer.vue";
  import { ref, onMounted, onUnmounted, computed } from "vue";
  import { useRouter, useRoute } from "vue-router";
  import { orderApi, walletApi } from "../api";
  import alipayImg from '@/assets/alipay.png';
  import wechatImg from '@/assets/wechat.png';

  const router = useRouter();
  const route = useRoute();
  const orderId = route.query.orderId;
  const orders = ref(null);
  const isShowDetailet = ref(false);
  const selectedPaymentMethod = ref('alipay'); // 默认选择支付宝
  const isPaymentProcessing = ref(false); // 支付处理状态

  const init = async () => {
	console.log('Payment页面初始化，订单ID:', orderId);
  
	try {
	  // 使用新的API获取订单详情
	  const orderData = await orderApi.getOrderById(orderId);
	  orders.value = orderData;
	  console.log('获取订单详情成功:', orders.value);
	} catch (error) {
	  console.error('获取订单详情失败:', error);
	  alert('获取订单信息失败，请重试！');
	}
  };

  init();
  
  // 防止用户通过浏览器后退按钮离开支付页面
  const handlePopState = () => {
	if (confirm('您确定要离开支付页面吗？订单可能无法完成支付。')) {
	  router.push({ path: "/index" });
	} else {
	  // 如果用户选择不离开，重新添加历史记录
	  history.pushState(null, null, location.href);
	}
  };

  onMounted(() => {
	// 添加历史记录并设置监听
	history.pushState(null, null, location.href);
	window.addEventListener('popstate', handlePopState);
  });
  
  onUnmounted(() => {
	// 清理事件监听器
	window.removeEventListener('popstate', handlePopState);
  });
  
  // 切换订单详情的显示和隐藏
  const detailetShow = () => {
	isShowDetailet.value = !isShowDetailet.value;
	console.log('订单详情显示状态:', isShowDetailet.value);
  };

  // 计算订单项目总价
  const calculateItemTotal = (detail) => {
	if (!detail || !detail.food) return '0.00';
	const price = detail.food.foodPrice || 0;
	const quantity = detail.quantity || 0;
	return (price * quantity).toFixed(2);
  };

  // 计算属性：获取订单详情
  const orderDetails = computed(() => {
	if (!orders.value || !orders.value.orderDetailets) return [];
	return orders.value.orderDetailets || [];
  });

  // 选择支付方式
  const selectPaymentMethod = (method) => {
	console.log('选择支付方式:', method);
	selectedPaymentMethod.value = method;
  };

  // 获取支付方式显示名称
  const getPaymentMethodName = () => {
    if (selectedPaymentMethod.value === 'alipay') return '支付宝';
    if (selectedPaymentMethod.value === 'wechat') return '微信支付';
    if (selectedPaymentMethod.value === 'wallet') return '钱包支付';
    return '在线支付';
  };

  // 确认支付
  const confirmPayment = async () => {
    if (!orders.value) {
      alert('订单信息加载中，请稍后重试！');
      return;
    }

    if (isPaymentProcessing.value) {
      return; // 防止重复点击
    }

    const paymentMethodName = getPaymentMethodName();
    
    if (!confirm(`确认使用${paymentMethodName}支付 ¥${orders.value.orderTotal} 吗？`)) {
      return;
    }

    isPaymentProcessing.value = true;
    console.log('开始支付流程:', {
      orderId: orderId,
      paymentMethod: selectedPaymentMethod.value,
      amount: orders.value.orderTotal
    });

    if (selectedPaymentMethod.value === 'wallet') {
      try {
        const ok = await walletApi.checkBalanceSufficient(orders.value.orderTotal);
        if (!ok) {
          alert('钱包余额不足，请先充值');
          isPaymentProcessing.value = false;
          return;
        }
        await updateOrderStatus(2);
        alert('钱包支付成功，订单已标记为已支付');
        router.push({ path: '/orderList' });
      } catch (e) {
        console.error('钱包支付失败:', e);
        alert(`钱包支付失败：${e.message || '请稍后重试'}`);
        isPaymentProcessing.value = false;
      }
    } else {
      // 第三方支付模拟
      simulatePayment();
    }
  };

  // 模拟支付过程
  const simulatePayment = () => {
	const paymentMethodName = getPaymentMethodName();
	
	// 显示支付处理中的提示
	alert(`正在跳转到${paymentMethodName}支付页面...`);
	
	// 模拟支付延迟
	setTimeout(() => {
	  // 随机模拟支付成功或失败（90%成功率）
	  const isSuccess = Math.random() > 0.1;
	  
	  if (isSuccess) {
		// 支付成功，立即更新订单状态
		updateOrderStatus(2).then(updateSuccess => {
		  if (updateSuccess) {
			console.log('订单状态更新成功，准备跳转页面');
			// 刷新页面上的订单数据
			init();
		  } else {
			console.warn('订单状态更新失败，但支付已成功');
		  }
		  
		  // 无论订单状态更新是否成功，都提示用户支付成功并询问跳转
		  if (confirm('支付成功！订单已完成。\n\n是否查看订单列表？')) {
			// 用户选择查看订单列表
			router.push({ 
			  path: '/orderList'
			});
		  } else {
			// 用户选择返回首页
			router.push({ path: '/index' });
		  }
		});
	  } else {
		// 支付失败
		alert('支付失败，请重试！');
		isPaymentProcessing.value = false;
	  }
	}, 2000); // 2秒后完成支付
  };

  // 更新订单状态
  const updateOrderStatus = async (newStatus) => {
	console.log(`开始更新订单${orderId}状态为:`, newStatus);
  
	try {
	  // 使用新的API更新订单状态
	  const updatedOrder = await orderApi.updateOrderStatus(orderId, newStatus);
	  console.log('订单状态更新成功:', updatedOrder);
	  return true;
	} catch (error) {
	  console.error('订单状态更新失败:', error);
	  return false;
	}
  };

  // 返回上一页
  const goBack = () => {
    // 获取当前订单关联的商家ID
    const businessId = orders.value?.business?.id;
    
    // 直接导航到确认订单页面，而不是使用router.go(-1)
    router.push({
      path: '/orders',
      query: { 
        businessId: businessId
      }
    });
  };
  </script>
  
  <style scoped>
  /****************** 总容器 ******************/
  .wrapper {
	width: 100%;
	height: 100%;
  }
  
  /****************** 加载状态 ******************/
  .loading {
	width: 100%;
	padding: 8vw 4vw;
	text-align: center;
	color: #666;
	font-size: 4vw;
  }
  
  /****************** header部分 ******************/
  .wrapper header {
	width: 100%;
	height: 12vw;
	background-color: #0097ff;
	color: #fff;
	font-size: 4.8vw;
  
	position: fixed;
	left: 0;
	top: 0;
	z-index: 1000;
  
	display: flex;
	justify-content: center;
	align-items: center;
  }

  .wrapper header i {
	position: absolute;
	left: 3vw;
	font-size: 6vw;
	color: #fff;
	cursor: pointer;
  }
  
  /****************** 订单信息部分 ******************/
  .wrapper h3 {
	margin-top: 12vw;
	box-sizing: border-box;
	padding: 4vw 4vw 0;
  
	font-size: 4vw;
	font-weight: 300;
	color: #999;
  }
  
  .wrapper .order-info {
	box-sizing: border-box;
	padding: 4vw;
	font-size: 4vw;
	color: #666;
  
	display: flex;
	justify-content: space-between;
	align-items: center;
  }
  
  .wrapper .order-info p:last-child {
	color: orangered;
  }
  
  /****************** 订单明细部分 ******************/
  .order-detailet {
	width: 100%;
	margin-bottom: 4vw;
	background-color: #f8f8f8;
	border-radius: 2vw;
	padding: 2vw 4vw;
}

.order-detailet li {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 2vw 0;
	border-bottom: 1px solid #eee;
}

.order-detailet li:last-child {
	border-bottom: none;
}

.order-detailet li p {
	font-size: 3.2vw;
	color: #333;
}

.order-detailet li p:nth-child(2) {
	color: #ff6b35;
	font-weight: bold;
}

.fa-caret-right, .fa-caret-down {
	margin-left: 2vw;
	color: #999;
	transition: all 0.3s;
}
  
  /****************** 支付方式部分 ******************/
  .wrapper .payment-type {
	width: 100%;
  }
  
  .wrapper .payment-type li {
    width: 100%;
    box-sizing: border-box;
    padding: 4vw;
    cursor: pointer;
    transition: all 0.3s ease;
    border-bottom: 1px solid #f0f0f0;
    
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .wrapper .payment-type li:hover {
	background-color: #f9f9f9;
  }
  
  .wrapper .payment-type li:active {
	background-color: #e6f7ff;
	transform: scale(0.98);
  }
  
  .wrapper .payment-type li.selected {
	background-color: #f0f8ff;
	border-left: 4px solid #38ca73;
  }
  
  .wrapper .payment-type li img {
    width: 33vw;
    height: 8.9vw;
  }

  .wallet-option {
    gap: 2vw;
  }
  .wallet-option .wallet-icon {
    font-size: 7vw;
    color: #0097ff;
  }
  .wallet-option .wallet-text {
    font-size: 4vw;
    color: #333;
    flex: 1;
  }
  
  .wrapper .payment-type li .fa-check-circle {
	font-size: 5vw;
	color: #38ca73;
	transition: all 0.3s ease;
  }
  
  .wrapper .payment-button {
	width: 100%;
	box-sizing: border-box;
	padding: 4vw;
  }
  
  .wrapper .payment-button button {
	width: 100%;
	height: 10vw;
	border: none;
	/*去掉外轮廓线*/
	outline: none;
	border-radius: 4px;
	background-color: #38ca73;
	color: #fff;
	font-size: 4.5vw;
	font-weight: 700;
	cursor: pointer;
	transition: all 0.3s ease;
  }
  
  .wrapper .payment-button button:hover:not(:disabled) {
	background-color: #2eb85c;
	transform: translateY(-1px);
  }
  
  .wrapper .payment-button button:disabled {
	background-color: #ccc;
	cursor: not-allowed;
	transform: none;
  }
  
  .wrapper .payment-button button:active:not(:disabled) {
	transform: translateY(0);
  }
  </style>
